package com.rainy.generator.interceptor;


import com.rainy.generator.common.config.JsonConfig;
import com.rainy.generator.entity.MainMenu;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.ModelMap;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author liuqin on 2017/12/17
 */
public class RequestInterceptor implements HandlerInterceptor{

    @Value("${server.domain}")
    private String domain;

    @Resource
    private JsonConfig jsonConfig;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        System.out.println("preHandle");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
       if (!isAjaxRequest(httpServletRequest)) {
           String uri = httpServletRequest.getRequestURI();
           if (modelAndView!=null) {
               ModelMap modelMap = modelAndView.getModelMap();
               modelMap.put("domain", domain);
               List<MainMenu> mainMenus = jsonConfig.getConfigArray(jsonConfig.getMenu(),MainMenu.class);
               tag:
               for (MainMenu mainMenu : mainMenus) {
                   for (MainMenu.SubMenu subMenu : mainMenu.getSubMenus()) {
                       if (subMenu.getActiveUrls().contains(uri)) {
                           subMenu.setActive(true);
                           mainMenu.setActive(true);
                           break tag;
                       }
                   }
               }
               modelMap.put("menus", mainMenus);
               System.out.println("posthandle");
           }
       }
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        System.out.println("afterCompletion");
    }
    private boolean isAjaxRequest(HttpServletRequest request) {
        if (!"XMLHttpRequest".equalsIgnoreCase(request.getHeader("X-Requested-With"))
                && request.getParameter("ajax") == null) {
            return false;
        }
        return true;
    }
}
